package gs.wicket.app;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Mailer {

	private static String SENDER_EMAIL = "shminkagiftshop@gmail.com";
	private static String SENDER_PASSWORD = "Giftshop";

	private static Properties MAIL_SERVER_PROPERTIES = new Properties();
	static {
		MAIL_SERVER_PROPERTIES.put("mail.smtp.host", "smtp.gmail.com");
		MAIL_SERVER_PROPERTIES.put("mail.smtp.auth", "true");
		MAIL_SERVER_PROPERTIES.put("mail.debug", "true");
		MAIL_SERVER_PROPERTIES.put("mail.smtp.port", "465");
		MAIL_SERVER_PROPERTIES.put("mail.smtp.socketFactory.port", "465");
		MAIL_SERVER_PROPERTIES.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		MAIL_SERVER_PROPERTIES.put("mail.smtp.socketFactory.fallback", "false");
		MAIL_SERVER_PROPERTIES.put("mail.debug", "false");

	}

	public void sendEmail(String fromEmail, String subject, String htmlContent, boolean enableCC) throws Exception {
		// check for exceptions
		if (subject == null) {
			throw new Exception("Subject null.");
		}
		if (fromEmail == null) {
			throw new Exception("From email null.");
		}
		if (htmlContent == null) {
			throw new Exception("Content null.");
		}

		// creating session
		Session session = Session.getDefaultInstance(MAIL_SERVER_PROPERTIES, new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(SENDER_EMAIL, SENDER_PASSWORD);
			}
		});
		
		Message msg = new MimeMessage(session);

		// email attenders
		InternetAddress addressFrom = new InternetAddress(SENDER_EMAIL);
		InternetAddress addressTo = new InternetAddress(Mailer.SENDER_EMAIL);
		InternetAddress addressCc = new InternetAddress(fromEmail);

		msg.setFrom(addressFrom);
		msg.setRecipient(Message.RecipientType.TO, addressTo);
		if (enableCC){
			msg.setRecipient(Message.RecipientType.CC, addressCc);
		}
		
		// subject and content
		msg.setSubject(subject);
		msg.setContent(htmlContent, "text/html; charset=UTF-8");
		
		// sending an email 
		Transport.send(msg);
	}
}
